package cn.yjr.vector;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.yjr.vector.tools.BitmapHelper;
import cn.yjr.vector.tools.FileHelper;
import cn.yjr.vector.tools.MD5;
import cn.yjr.vector.tools.SharedPreferencesHelper;
import cn.yjr.vector.tools.YJRHttpClient;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class UpdateGzzActivity extends SherlockActivity implements OnClickListener{

	LayoutInflater inflater;
	ActionBar actionBar;
	View title_bar;
	Context context;
	String response;
	JSONObject jsonInfo;
	FileHelper fileHelper;
	String certificate_num = "无";
	SharedPreferencesHelper spHelper;
	TextView upload_tv, save_tv;
	ImageView certificate_imv;
	JSONObject userData;
	DisplayImageOptions options;
	String wc_path;
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update_gzz);
		inflater = this.getLayoutInflater();
		actionBar = getSupportActionBar();
		context = this;
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.me_jobinfo)
		.showImageForEmptyUri(R.drawable.me_appointment)
		.showImageOnFail(R.drawable.head)
		.cacheInMemory(true)
		.cacheOnDisc(true)
		.considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.build();
		Intent intent = this.getIntent();
		try {
			userData = new JSONObject(intent.getStringExtra("userData"));
			wc_path = userData.getString("wcPath");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.spHelper = new SharedPreferencesHelper(this.context);
		this.fileHelper = new FileHelper(this.context);
		initTitleBar();
		
		initComponent();
		
		initEventListener();
		
		
		
	
	}
	
	private void initTitleBar(){
		ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,ActionBar.LayoutParams.WRAP_CONTENT,Gravity.CENTER);
		title_bar = inflater.inflate(R.layout.update_gzz_action_bar, null);
		
		actionBar.setCustomView(title_bar,lp);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
	}
	private void initComponent(){
		upload_tv = (TextView) findViewById(R.id.upload_tv);
		certificate_imv = (ImageView) findViewById(R.id.certificate_imv);
		save_tv = (TextView) title_bar.findViewById(R.id.save);
		
		imageLoader.displayImage("http://115.28.222.1/yijiaren/pics/certs/"+wc_path, certificate_imv, options);

	}
	
	private void initEventListener(){
		
		upload_tv.setOnClickListener(this);
		certificate_imv.setOnClickListener(this);
		save_tv.setOnClickListener(this);
		
	}

	  private void ShowPickDialog() {  
	      new AlertDialog.Builder(this)  
	              .setTitle("上传资格证书")  
	              .setNegativeButton("相册", new DialogInterface.OnClickListener() {  
	                  public void onClick(DialogInterface dialog, int which) {  
	                      dialog.dismiss();  
	                      /**  
	                       * 刚开始，我自己也不知道ACTION_PICK是干嘛的，后来直接看Intent源码，  
	                       * 可以发现里面很多东西，Intent是个很强大的东西，大家一定仔细阅读下  
	                       */ 
	                      Intent intent = new Intent(Intent.ACTION_PICK, null);  
	                        
	                      /**  
	                       * 下面这句话，与其它方式写是一样的效果，如果：  
	                       * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);  
	                       * intent.setType(""image/*");设置数据类型  
	                       * 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"  
	                       * 这个地方小马有个疑问，希望高手解答下：就是这个数据URI与类型为什么要分两种形式来写呀？有什么区别？  
	                       */ 
	                      intent.setDataAndType(  
	                              MediaStore.Images.Media.EXTERNAL_CONTENT_URI,  
	                              "image/*");  
	                      startActivityForResult(intent, 1);  

	                  }  
	              })  
	              .setPositiveButton("拍照", new DialogInterface.OnClickListener() {  
	                  public void onClick(DialogInterface dialog, int whichButton) {  
	                      dialog.dismiss();  
	                      /**  
	                       * 下面这句还是老样子，调用快速拍照功能，至于为什么叫快速拍照，大家可以参考如下官方  
	                       * 文档，you_sdk_path/docs/guide/topics/media/camera.html  
	                       * 我刚看的时候因为太长就认真看，其实是错的，这个里面有用的太多了，所以大家不要认为  
	                       * 官方文档太长了就不看了，其实是错的，这个地方小马也错了，必须改正  
	                       */  
	                      Intent intent = new Intent(  
	                              MediaStore.ACTION_IMAGE_CAPTURE);  
	                      //下面这句指定调用相机拍照后的照片存储的路径  
	                      intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri  
	                              .fromFile(new File(fileHelper.appFilePath + "pic/",  
	                                      "gzz.jpeg")));  
	                      startActivityForResult(intent, 2);  
	                  }  
	              }).show();  
	  }  
	
	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.upload_tv:
			ShowPickDialog();
			break;
		case R.id.save:
			try {
				upload();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		default:
			break;
		}
		
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
	      switch (requestCode) {
	      // 如果是直接从相册获取  
	      case 1: 
	    	  if(resultCode == Activity.RESULT_OK && null!=data)
	    	  {
	    		Uri selectedImage = data.getData();
	  			Log.v("weiyi",selectedImage.toString());
	  			ContentResolver resolver = this.getContentResolver();
	  			String[] filePathColumns = {MediaStore.Images.Media.DATA};
	  			Cursor cursor = resolver.query(selectedImage, filePathColumns, null, null, null);
	  			cursor.moveToFirst();
	  			int columnIndex = cursor.getColumnIndex(filePathColumns[0]);
	  			String picturePath = cursor.getString(columnIndex);
	  			/**
	  			 * 这里获取图片可能会有两个问题，一是oom，二是Bitmap too large to be uploaded into a texture
	  			 * 第一个问题的解决办法：使用BitmapFactory.Options这个类。
	  			 * options有一个属性：boolean android.graphics.BitmapFactory.Options.inJustDecodeBounds
	  			 * 第二个问题的解决办法 http://developer.android.com/reference/android/graphics/BitmapRegionDecoder.html
	  			 * 第一种解决方法就可以直接解决了参考bitmapHelper类中的实现
	  			 * reference：http://blog.csdn.net/ta893115871/article/details/13750605
	  			 */
	    		Log.v("weiyi",picturePath);
	    		Bitmap bt = BitmapFactory.decodeFile(picturePath);
	    		ByteArrayOutputStream output = new ByteArrayOutputStream();//初始化一个流对象
	            bt.compress(CompressFormat.JPEG, 100, output);
	            byte[] b = output.toByteArray();
	    		try {
					this.fileHelper.writeSDFile("pic", "gzz.jpeg").write(b);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    		
	  			Bitmap bitmap = BitmapHelper.getSmallBitmap(picturePath, 100, 100);
	  			cursor.close();
	  			certificate_imv.setImageBitmap(bitmap);
	    	  }
	          break;  
	      // 如果是调用相机拍照时  
	      case 2:  
    		  //Bundle bundle = data.getExtras();
  			  //获取相机返回的数据，并转换为图片格式
  			  //Bitmap bitmap = (Bitmap) bundle.get("data");
    		  Log.v("weiyi",fileHelper.appFilePath+"/pic");
  			  Bitmap bitmap = BitmapHelper.getSmallBitmap(fileHelper.appFilePath + "pic/gzz.jpeg", 100, 100);
  			  certificate_imv.setImageBitmap(bitmap);
	          break;  
	      default:  
	          break;  

	      }  
	      super.onActivityResult(requestCode, resultCode, data);  
	  }  
	
	private void upload() throws FileNotFoundException{
		RequestParams params = new RequestParams(); 
		File file = new File(fileHelper.appFilePath
                + "pic/gzz.jpeg"); 
		params.add("fileFileName","gzz.jpeg");
		params.add("fileType","wc");
	    params.put("file", file);  
        YJRHttpClient.post(context,"/doctor/updateCert", params, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {
						if(jsonInfo.getInt("result") == 1){
							YJRHttpClient.setCookie(context); 
							Toast.makeText(context, "上传资格证书成功", Toast.LENGTH_LONG).show();
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
		});
	}
	

}